<!--
 * @Author: 宋绍华
 * @Date: 2024-12-03 16:15:28
 * @LastEditors: 宋绍华
 * @LastEditTime: 2025-01-07 16:45:24
 * @FilePath: \sr_system_manager_ui\src\views\project\components\MyProject\BtnRender.vue
 * @Description: 
-->
<template>
  <div class="flex flex-wrap items-center leading-none">
    <template v-if="!onlyShowRecord">
      <el-button v-hasPermi="viewPermission" link type="primary" v-if="showViews"
        @click="router.push({ path: '/project/mine/edit', query: { projectNature: record?.projectNature, projectId: record?.id, mode: 'view', projectName: record?.projectName } })">查看</el-button>

      <!-- 纵向项目、校级项目 -->
      <template v-if="projectNature !== projectNatureEnum.projectNatureHorizontal">
        <!-- 管理员 -->
        <template v-if="role !== 'NORMAL'">
          <el-button v-hasPermi="[`${perMissMainStr}:EOL`]" v-if="[
          projectStatusEnum.projectApproval,
          projectStatusEnum.auditAudit,
          projectStatusEnum.zjAuditApproval,
          projectStatusEnum.auditUnAudit,
          projectStatusEnum.auditPass,
          projectStatusEnum.constructionWaitApproval,
          projectStatusEnum.initialReviewFailed,
          projectStatusEnum.constructionWaitReview,
          projectStatusEnum.changeWaitApproval,
          projectStatusEnum.conclusionUnPass,
          projectStatusEnum.changeWait,
        ].includes(record?.status)" @click="stopProject(record)" link type="primary">项目终止</el-button>
          <el-button v-hasPermi="[`${perMissMainStr}:applicationAudit`]"
            v-if="projectStatusEnum.submitApproval === record?.status" link type="primary"
            @click="router.push({ path: '/project/mine/edit', query: { role: 'ADMIN', projectNature: record?.projectNature, showReviewProcess: true, status: record.status, checkType: 1, pType: 1, projectId: record?.id, mode: 'view', type: 5, projectName: record?.projectName } })">申报审核</el-button>
          <el-button v-hasPermi="[`${perMissMainStr}:approvalAudit`]"
            v-if="projectStatusEnum.auditApproval === record?.status && showAudit" link type="primary"
            @click="router.push({ path: '/project/mine/edit', query: { role: 'ADMIN', projectNature: record?.projectNature, showReviewProcess: true, checkType: 1, pType: 5, projectId: record?.id, mode: 'view', type: 5, projectName: record?.projectName } })">立项审核</el-button>
          <el-button v-hasPermi="[`${perMissMainStr}:startMidInspection`]"
            v-if="projectStatusEnum.projectApproval === record?.status" link type="primary"
            @click="handleCheck(1, record)">开启中检</el-button>
          <el-button v-hasPermi="[`${perMissMainStr}:midInspectionAudit`]"
            v-if="projectStatusEnum.zjAuditApproval === record?.status" link type="primary"
            @click="linkToPage(record, 2)">中检审核</el-button>
          <el-button v-if="projectStatusEnum.conclusionWait === record?.status" link type="primary"
            @click="onFinalReview(record)">结项审核</el-button>
          <el-button v-hasPermi="[`${perMissMainStr}:alterAudit`]"
            v-if="projectStatusEnum.changeWait === record?.status" link type="primary"
            @click="changeReview(record)">变更审核</el-button>
          <el-button v-hasPermi="[`${perMissMainStr}:finalFirstAudit`]"
            v-if="projectStatusEnum.constructionWaitApproval === record?.status" link type="primary"
            @click="onProjectWaitApproval(record)">结项初审</el-button>
          <el-button v-hasPermi="[`${perMissMainStr}:finalAssess`]" @click="onProjectWaitApproval(record, 2)"
            v-if="projectStatusEnum.constructionWaitReview === record?.status" link type="primary">结项评审</el-button>
        </template>
        <template v-else>
          <el-button link type="primary" v-hasPermi="['myProject:edit']"
            v-if="!hideEdit && [projectStatusEnum.submitWait, projectStatusEnum.submitAudit, projectStatusEnum.projectApprovalWait].includes(record?.status)"
            @click="onEdit(record)">编辑</el-button>
          <el-button link type="primary" v-hasPermi="['myProject:file']"
            v-if="[projectStatusEnum.projectApproval, projectStatusEnum.auditAudit, projectStatusEnum.zjAuditApproval, projectStatusEnum.auditUnAudit, projectStatusEnum.auditPass, projectStatusEnum.conclusionUnPass].includes(record?.status)"
            @click="router.push({ path: '/project/mine/edit', query: { projectNature: record?.projectNature, projectId: record.id, type: 4, status: record?.status, mode: 'view', projectName: record.projectName } })">文档</el-button>
          <el-button link type="primary" v-hasPermi="['myProject:submitApproval']"
            v-if="[projectStatusEnum.submitUnAudit, projectStatusEnum.projectApprovalWait, projectStatusEnum.projectAudit].includes(record?.status)"
            @click="goToProject(record)">提交立项</el-button>
          <el-button v-hasPermi="['myProject:submitFinal']" link type="primary"
            v-if="[projectStatusEnum.projectApproval, projectStatusEnum.auditPass, projectStatusEnum.initialReviewFailed, projectStatusEnum.changeWaitApproval, projectStatusEnum.conclusionUnPass].includes(record?.status)"
            @click="router.push({ path: '/project/mine/submitConclusion', query: { status: record?.status, projectId: record.id, projectName: record.projectName } })">
            {{ [projectStatusEnum.projectApproval, projectStatusEnum.auditPass].includes(record?.status) ? '发起结项' :
            '提交结项'
            }}
          </el-button>
          <el-button v-hasPermi="['myProject:submitApplication']"
            v-if="[projectStatusEnum.submitAudit, projectStatusEnum.submitWait].includes(record?.status)" link
            type="primary" @click="handleCheck(2, record)">提交申报</el-button>
          <el-button link type="primary" v-hasPermi="['myProject:submitMidInspection']"
            v-if="[projectStatusEnum.auditAudit, projectStatusEnum.auditUnAudit,].includes(record?.status)"
            @click="router.push({ path: '/project/mine/submitIntermediateInspection', query: { projectId: record.id, projectName: record.projectName } })">提交中检</el-button>
          <el-button link type="primary" v-hasPermi="['myProject:alter']"
            v-if="[projectStatusEnum.projectApproval, projectStatusEnum.auditPass, projectStatusEnum.conclusionUnPass].includes(record?.status)"
            @click="router.push({ path: '/project/mine/initiateChange', query: { projectId: record.id, projectName: record.projectName } })">发起变更</el-button>
          <el-button v-hasPermi="['myProject:del']"
            v-if="[projectStatusEnum.submitWait, projectStatusEnum.submitAudit, projectStatusEnum.projectApprovalWait].includes(record?.status)"
            link type="danger" @click="onDelete(record)">删除</el-button>
        </template>
      </template>
      <template v-else>
        <template v-if="role !== 'NORMAL'">
          <el-button v-if="[
          projectStatusEnum.projectApproval,
          projectStatusEnum.constructionWaitApproval,
          projectStatusEnum.initialReviewFailed,
          projectStatusEnum.constructionWaitReview,
          projectStatusEnum.changeWaitApproval,
          projectStatusEnum.conclusionUnPass,
          projectStatusEnum.changeWait,
        ].includes(record?.status)" @click="stopProject(record)" link type="primary">项目终止</el-button>
          <el-button v-hasPermi="['project:horizontalManage:horizontalManage:contractAudit']"
            v-if="projectStatusEnum.contractApproval === record?.status" link type="primary"
            @click="router.push({ path: '/project/mine/edit', query: { role: 'ADMIN', projectNature: record?.projectNature, showReviewProcess: true, status: record.status, checkType: 1, pType: 1, projectId: record?.id, mode: 'view', type: 5, projectName: record?.projectName } })">合同审核</el-button>
          <el-button v-hasPermi="['project:horizontalManage:horizontalManage:budgetAudit']"
            v-if="projectStatusEnum.budgetApproval === record?.status" link type="primary"
            @click="router.push({ path: '/project/manage/budgetReview', query: { projectId: record?.id, projectName: record?.projectName } })">预算审核</el-button>
          <el-button v-if="projectStatusEnum.conclusionWait === record?.status" link type="primary"
            @click="onFinalReview(record)">结项审核</el-button>
          <el-button v-hasPermi="['project:horizontalManage:horizontalManage:alterAudit']"
            v-if="projectStatusEnum.changeWait === record?.status" link type="primary"
            @click="changeReview(record)">变更审核</el-button>
          <el-button v-hasPermi="['project:horizontalManage:horizontalManage:finalFirstAudit']"
            v-if="projectStatusEnum.constructionWaitApproval === record?.status" link type="primary"
            @click="onProjectWaitApproval(record)">结项初审</el-button>
          <el-button v-hasPermi="['project:horizontalManage:horizontalManage:finalAssess']"
            @click="onProjectWaitApproval(record, 2)" v-if="projectStatusEnum.constructionWaitReview === record?.status"
            link type="primary">结项评审</el-button>
        </template>
        <template v-else>
          <el-button link type="primary" v-hasPermi="['myProject:edit']"
            v-if="!hideEdit && [projectStatusEnum.contractWait, projectStatusEnum.contractAudit].includes(record?.status)"
            @click="onEdit(record)">编辑</el-button>
          <el-button link type="primary" v-hasPermi="['myProject:file']"
            v-if="[projectStatusEnum.projectApproval, , projectStatusEnum.conclusionUnPass].includes(record?.status)"
            @click="router.push({ path: '/project/mine/edit', query: { projectNature: record?.projectNature, projectId: record.id, type: 4, status: record?.status, mode: 'view', projectName: record.projectName } })">文档</el-button>
          <el-button link type="primary" v-hasPermi="['myProject:submitApplication']"
            v-if="[projectStatusEnum.contractWait, projectStatusEnum.contractAudit].includes(record?.status)"
            @click="goToProject(record)">提交合同</el-button>
          <el-button link type="primary"
            v-if="[projectStatusEnum.budgetWait, projectStatusEnum.budgetAudit].includes(record?.status)"
            @click="router.push({ path: '/project/mine/submitBudget', query: { projectId: record?.id, projectName: record?.projectName } })">提交预算</el-button>

          <el-button link type="primary" v-hasPermi="['myProject:submitFinal']"
            v-if="[projectStatusEnum.changeWaitApproval, projectStatusEnum.initialReviewFailed, projectStatusEnum.projectApproval, projectStatusEnum.conclusionUnPass].includes(record?.status)"
            @click="router.push({ path: '/project/mine/submitConclusion', query: { status: record?.status, projectId: record.id, projectName: record.projectName } })">
            {{ [projectStatusEnum.projectApproval, projectStatusEnum.auditPass].includes(record?.status) ? '发起结项' :
            '提交结项'
            }}</el-button>
          <el-button link type="primary" v-hasPermi="['myProject:alter']"
            v-if="[projectStatusEnum.projectApproval, , projectStatusEnum.conclusionUnPass].includes(record?.status)"
            @click="router.push({ path: '/project/mine/initiateChange', query: { projectId: record.id, projectName: record.projectName } })">发起变更</el-button>

          <el-button v-hasPermi="['myProject:del']"
            v-if="[projectStatusEnum.contractWait, projectStatusEnum.contractAudit].includes(record?.status)" link
            type="danger" @click="onDelete(record)">删除</el-button>
        </template>
      </template>
    </template>

    <el-button v-hasPermi="recordPermission" link type="primary"
      @click="auditRecordVisible = true, curPid = record?.id">审核记录</el-button>

    <!-- 日志 -->
    <AuditRecordDrawer v-model:visible="auditRecordVisible" :project-id="curPid" v-if="auditRecordVisible" />
  </div>
</template>

<script setup lang="ts">
import { projectNatureEnum, projectStatusEnum } from '@/utils/constEnum'
// import useUserStore from '@/store/modules/user'
import AuditRecordDrawer from '@/components/AuditRecordDrawer/index.vue'
import { ElMessageBox } from 'element-plus';
import { projectApproveSubmitApi, projectDeleteApi, submitApproveInitiateApi } from '@/api/project';
import { BaseSuccessRespDTO } from '@/api/project/types';

// const userStore = useUserStore()
const emit = defineEmits(['update'])

const { proxy } = getCurrentInstance();

const auditRecordVisible = ref(false)
const curPid = ref('') // 当前项目id

const router = useRouter()
const props = defineProps({
  showAudit: { // 是否显示立项审核
    type: Boolean,
    default: true
  },
  hideView: { // 隐藏查看
    type: Boolean,
    default: false
  },
  hideEdit: { // 隐藏编辑
    type: Boolean,
    default: false
  },
  projectNature: {
    type: Number,
    default: 1
  },
  record: {
    type: Object,
    default: () => { }
  },
  role: {
    type: String as PropType<'NORMAL' | 'ADMIN'>,
    default: 'NORMAL'
  },
  onlyShowRecord: { // 只显示记录
    type: Boolean,
    default: false
  }
})

// 查看按钮权限
const viewPermission = computed(() => {
  if (props.role === 'NORMAL') {
    return ['myProject:view']
  } else {
    switch (props.projectNature) {
      case projectNatureEnum.projectNatureSchool:
        return ['project:school:schoolManage:view']
      case projectNatureEnum.projectNatureHorizontal:
        return ['project:horizontalManage:horizontalManage:view']
      default:
        return ['project:portrait:portraitManage:view']
    }
  }
})
// 审核记录查看
const recordPermission = computed(() => {
  if (props.role === 'NORMAL') {
    return ['myProject:auditRecord']
  } else {
    switch (props.projectNature) {
      case projectNatureEnum.projectNatureSchool:
        return ['project:school:schoolManage:auditRecord']
      case projectNatureEnum.projectNatureHorizontal:
        return ['project:horizontalManage:horizontalManage:auditRecord']
      default:
        return ['project:portrait:portraitManage:auditRecord']
    }
  }
})

const perMissMainStr = computed(() => {
  return props.projectNature === projectNatureEnum.projectNatureSchool ? 'project:school:schoolManage' : 'project:portrait:portraitManage'
})

const showViews = computed(() => {
  if (props.role !== 'NORMAL' && props.projectNature === projectNatureEnum.projectNatureHorizontal && projectStatusEnum.contractWait === props.record?.status) {
    return false
  }

  return !props.hideView
})

// 发起中检
const { runAsync: submitApproveInitiate, loading: approvalLoading } = useRequest(submitApproveInitiateApi, {
  manual: true,
  onSuccess: (response: BaseSuccessRespDTO) => {
    if (response.isSuccess) {
      return true
    }
  }
})

// 提交预算
const { runAsync: projectApproveSubmit, loading: approveSbLoading } = useRequest(projectApproveSubmitApi, {
  manual: true,
  debounceWait: 500,
  onSuccess: (res: BaseSuccessRespDTO) => {
    return res.isSuccess
  }
})

// 提交预算
const { runAsync: projectDelete, loading: deleteLoading } = useRequest(projectDeleteApi, {
  manual: true,
  debounceWait: 500,
  onSuccess: (res: BaseSuccessRespDTO) => {
    return res.isSuccess
  }
})

// 跳转发布消息通知
const linkToPage = (record, type?: number) => {
  if (type === 2) {
    router.push({
      name: 'IntermediateInspectionReview',
      query: {
        projectId: record?.id,
        projectNature: record?.projectNature,
        projectName: record?.projectName
      }
    })
  } else if (type === 3) {
    router.push({
      name: 'ConclusionReview',
      query: {
        projectId: record?.id,
        projectNature: record?.projectNature,
        projectName: record?.projectName
      }
    })
  } else if (type === 4) {
    router.push({
      name: 'ManagerBudgetReview',
      query: {
        projectId: record?.id,
        projectNature: record?.projectNature,
        projectName: record?.projectName
      }
    })
  } else {
    router.push({
      name: 'publishNotices',
      query: {
        projectId: record?.id,
        projectNature: record?.projectNature
      }
    })
  }
}

function handleCheck(type, row) {
  if (type === 1) {
    ElMessageBox.confirm('是否确认开启项目的中期检查？', "中期检查", {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      loading: approvalLoading.value,
      beforeClose: async (action, instance, done) => {
        if (action === 'confirm') {
          const isTrue = await submitApproveInitiate({ projectIds: [row.id], type: 3 })
          done(isTrue)
          if (isTrue) {
            ElMessage({
              message: '发起中检成功',
              type: 'success',
            })
            emit('update')
            if (props.hideView) {
              window.location.reload()
            }
          }
        } else {
          done()
        }
      }
    })
  } else {
    ElMessageBox.confirm('是否确认提交项目申报？', "提交申报", {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      loading: approveSbLoading.value,
      beforeClose: async (action, instance, done) => {
        if (action === 'confirm') {
          const isTrue = await projectApproveSubmit({ projectId: row.id, type: 1 })
          done(isTrue)
          if (isTrue) {
            ElMessage({
              type: 'success',
              message: '提交成功',
            })
            emit('update')
            if (props.hideView) {
              window.location.reload()
            }
          }
        } else {
          done()
        }
      }
    })
  }
}

// 跳转结项路由
const onFinalReview = (row) => {
  router.push({
    path: '/project/conclusion/conclusionReview',
    query: {
      projectId: row.id,
      mode: 'edit',
      projectName: row.projectName
    }
  })
}

// 变更审核
function changeReview(row) {
  router.push({
    name: 'ChangeReview',
    query: {
      projectName: row.projectName,
      projectId: row.id,
    }
  })
}

// 终止项目
const stopProject = (row) => {
  // 删除
  ElMessageBox.confirm('是否确认终止项目，终止后项目将无法恢复？', "", {
    confirmButtonClass: 'el-button--danger',
    confirmButtonText: '确认',
    loading: approveSbLoading.value,
    type: 'warning',
    beforeClose: async (action, instance, done) => {
      if (action === 'confirm') {
        const isTrue = await submitApproveInitiate({ projectIds: [row.id], type: 4 })
        done(isTrue)
        if (isTrue) {
          ElMessage({
            message: '操作成功',
            type: 'success',
          })
          emit('update')
          if (props.hideView) {
            window.location.reload()
          }
        }
      } else {
        done()
      }
    }
  })
}

// 删除
function onDelete(row) {
  ElMessageBox.confirm('是否确认删除？', "", {
    type: 'warning',
    confirmButtonClass: 'el-button--danger',
    confirmButtonText: '删除',
    loading: deleteLoading.value,
    beforeClose: async (action, instance, done) => {
      if (action === 'confirm') {
        const isTrue = await projectDelete({ id: row.id })
        done(isTrue)
        if (isTrue) {
          ElMessage({
            message: '删除成功',
            type: 'success',
          })
          emit('update')
          proxy.$tab.closePage()
        }
      } else {
        done()
      }
    }
  })
}

const onProjectWaitApproval = (record, type?: number) => {
  const { id, projectName } = record
  router.push({
    name: 'ConclusionWaitApproval',
    query: {
      projectId: id,
      projectName,
      type
    }
  })
}

// 去立项
const goToProject = (record) => {
  const { statisticsYear, projectType, noticeId, projectName, projectNature, id: projectId, status } = record
  router.push({ path: '/project/mine/create', query: { projectNature, projectName, projectType, projectId, status, statisticsYear, type: 0, mode: 'edit', noticeId } })
}

// 编辑
const onEdit = (record) => {
  const { noticeId, projectName, projectNature, id: projectId, status } = record
  let isProposal: any = undefined
  if (noticeId) {
    // 横向
    if (projectNature === projectNatureEnum.projectNatureHorizontal) {
      // 合同待提交、合同审核未通过状态 设置 isProposal 为 true
      isProposal = status === projectStatusEnum.contractWait || status === projectStatusEnum.contractAudit
    } else {
      // 纵向、校级
      // 申报待审核、申报审核未通过状态 设置 isProposal 为 true
      isProposal = status === projectStatusEnum.submitWait || status === projectStatusEnum.submitAudit
    }
  }
  router.push({ path: '/project/mine/edit', query: { isProposal, projectNature, projectId, type: 0, status, mode: 'edit', projectName } })
}

</script>

<style lang="scss">
.el-message-box__message {
  color: #1D2129;
}

.el-message-box {
  padding: 10px 20px 20px;
}
</style>